package com.relytosoft.mizar.media.common.emqx.client;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Jierry
 * @version 2022/4/22.
 */
public class MqttOp {

    private static final Logger log = LoggerFactory.getLogger(MqttOp.class);

//    /**
//     * 订阅主题
//     * @param topic 主题名称
//     */
//    public void subscribe(String topic) {
//        try {
//            MqttClient client = MqttPushClient.getClient();
//            if (client == null) {
//                return;
//            };
//            //client.subscribe(topic, 0);
//            //在订阅方法中作为参数使用
//            client.subscribe(topic, mqttMessageListener);
//            log.info("订阅主题:{}",topic);
//        } catch (MqttException e) {
//            e.printStackTrace();
//        }
//    }

    /**
     * 发布主题
     *
     * @param topic
     * @param pushMessage
     */
    public static void publish(String topic, String pushMessage) {

        log.info("SEND TO MQTT -- topic : {}, message : {}", topic, pushMessage);

        MqttMessage message = new MqttMessage();
        message.setQos(0);
        // 非持久化
        message.setRetained(false);
        message.setPayload(pushMessage.getBytes());
        MqttClient client = EmqxClient.getClient();
        if (client == null) {
            return;
        };
        MqttTopic mTopic = client.getTopic(topic);
        if (null == mTopic) {
            log.error("主题不存在:{}",mTopic);
        }
        try {
            mTopic.publish(message);
        } catch (Exception e) {
            log.error("mqtt发送消息异常:",e);
        }
    }

}
